import Promise from './bluebird.min.js'
var config = require('../config/config')

/**
 * 将小程序的API封装成支持Promise的API
 * @params fn {Function} 小程序原始API，如wx.login
 */
function promise(fn) {  
  return function (obj = {}) { 
    return new Promise((resolve, reject) => {      
      obj.success = function (res) {    
        resolve(res)
      }

      obj.fail = function (res) {
        reject(res)  
      }

      fn(obj)  
    })  
  }
}

//时间格式化
const formatTime = date => {
	const year = date.getFullYear()
	const month = date.getMonth() + 1
	const day = date.getDate()
	const hour = date.getHours()
	const minute = date.getMinutes()
	const second = date.getSeconds()

	return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

//日期转换
const getTime = (date, type = false) => {
	date = new Date(date)
	let Y = date.getFullYear(),
		M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1),
		D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
		h = date.getHours() < 10 ? '0' + date.getHours() : date.getHours(),
		m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes(),
		s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds(),
		ms = date.getMilliseconds() < 10 ? '0' + date.getMilliseconds() : date.getMilliseconds()
	let time = ''
	if(type) {
		time = Y + '-' + M + '-' + D
	} else {
		time = Y + '-' + M + '-' + D + ' ' + h + ':' + m + ':' + s
	}

	return time
}

//排序对比函数
const compare = (property) => {
	return function(a, b) {
		var value1 = a[property];
		var value2 = b[property];
		return value2 - value1;
	}
}

//日期数字补位
const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : '0' + n
}

//数组元素自动前移一位
const reArray = array => {
	let reArray = [],
		x = array.length
	for(var i = 0; i < array.length; i++) {
		reArray[x - 1] = array[i]
		x = x - 1
	}
	return reArray
}

//子字符串
const subStr = (string, length) => {
	return string.substr(0, length) + '……'
}

//是否在数组中
const inArray = (key, arr) => {
	let flag = false
	for(var i = 0; i <= arr.length; i++) {
		if(key == arr[i]) {
			flag = true
			break
		}
	}
	return flag
}

//显示进度条，微信限制，title最多6个字符
const showToast = (title, duration = 1000, icon = 'loading') => {
	wx.showToast({
		title: title,
		icon: icon,
		duration: duration
	})
}

// 显示失败提示
const showModel = (title, content, url = '../../pages/index/index', R = false) => {
	wx.showModal({
		title: title,
		content: content,
		showCancel: false,
		success: function(res) {
			if(R) {
				wx.redirectTo({
					url: url
				})
			} else {
				wx.navigateTo({
					url: url
				})
			}
		}
	})
}

//更新某个表的某个字段
const upData = (tableID, recordID, key, value) => {

	let Table = new wx.BaaS.TableObject(tableID)
	let table = Table.getWithoutData(recordID)

	table.uAppend(key, value)
	table.update().then((res) => {
		// success
		console.log(res)
		console.log(tableID + '_key:', value)
	}, (err) => {
		// err
		console.log(tableID + '_失败:', value)
	})
}

//获取龙币
const getCoin = (uID = 0) => {
	let MyUser = new wx.BaaS.User(),
		x = 0
	var reTimes = setInterval(function() {
		let userID = 0
		if(uID > 0) {
			userID = uID
		} else {
			userID = wx.BaaS.storage.get('uid')
		}
		// console.log('userID:' + userID)
		if(userID) {
			MyUser.get(userID).then((res) => {
				if(res.data.hasOwnProperty('coins') && res.data.coins !== null) {
					wx.BaaS.storage.set('coins', res.data.coins)
					console.log('币数:' + res.data.coins)
				} else {
					changeCoin(userID, 100, true, '老用户初始化100')
					wx.BaaS.storage.set('coins', 100)
					console.log('获取为空，老用户初始化100')
				}
			})
			clearTimeout(reTimes) //终止计时器
		}

		if(x >= 10) {
			clearTimeout(reTimes) //终止计时器
			return false
		} else {
			x = x + 1
		}
	}, 3000)
}

//龙币操作
const changeCoin = (userID, nums, act = false, text = '', obj = false) => {
	//获取当前值
	let MyUser = new wx.BaaS.User()
	MyUser.get(userID).then((user) => {
		// success
		let old = user.data
		let coins = old.coins * 1
		if(act) {
			coins = coins + nums
		} else {
			coins = coins - nums
		}

		let currentUser = MyUser.getCurrentUserWithoutData()

		currentUser.set('coins', coins).update().then((res) => {
			// success
			let re = res.data.coins - old.coins
			if(re > 0) {
				re = '+' + re
			}

			wx.BaaS.storage.set('coins', res.data.coins)
			showToast('金币 ' + re)

			if(obj) {
				log(1, text + '，金币' + re, obj) //日志记录
			} else {
				log(1, text + '，金币' + re) //日志记录
			}
		}, (err) => {
			// err
			showToast('coins fail', 600)
		})

	}, (err) => {
		// err
	})
}

//日志存储
const log = (type = 0, desc = 'System', obj = '') => {
	let Log = new wx.BaaS.TableObject(config.Table.Log)
	let log = Log.create()

	let newlog = {
		type: type,
		desc: desc,
		obj: obj
	}
	log.set(newlog).save().then((res) => {
		// success
		//     console.log('日志Ok', res.data)
	}, (err) => {
		showToast('日志存储失败', 600)
		// err
	})
}


module.exports = {
	promise: promise,
	compare: compare,
	formatTime: formatTime,
	getTime: getTime,
	reArray: reArray,
	subStr: subStr,
	inArray: inArray,
	showModal: showModel,
	showToast: showToast,
	upData: upData,
	changeCoin: changeCoin,
	getCoin: getCoin,
	log: log
}